package mobile.android.portal.ui;

import java.net.ConnectException;

import mobile.android.portal.R;
import mobile.android.portal.obj.Categories;
import mobile.android.portal.obj.Materials;
import mobile.android.portal.util.Functions;
import mobile.android.portal.webservice.BusinessPortalWebService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddProductInformationActivity extends Activity {

	Spinner select_cateogry_spinner;
	Spinner select_material_spinner;

	EditText productNameEditText, priceEditText, quantityEditText;

	Handler getDataHandler;
	Handler addProductHandler;

	Categories categories;
	Materials materials;

	/* Variable to store the id of the selected category */
	public static int selectedCategoryId;

	/* Variable to store the id of the selected material */
	public static int selectedMaterialId;

	/* declaring progress dialog */
	ProgressDialog progressDialog;

	/*
	 * Declaring alert dialog to indicate if it is not possible to connect with
	 * the web service
	 */
	AlertDialog connectionFailedAlert;
	/* Declaring alert dialog to indicate if user has entered invalid input data */
	AlertDialog userInputValidateAlert;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_insert_product_info);

		select_cateogry_spinner = (Spinner) findViewById(R.id.category_spinner);
		select_material_spinner = (Spinner) findViewById(R.id.material_spinner);
		productNameEditText = (EditText) findViewById(R.id.productNameEditText);
		quantityEditText = (EditText) findViewById(R.id.quantityEditText);
		priceEditText = (EditText) findViewById(R.id.priceEditText);

		progressDialog = Functions.getProgressDialog(this, "Please wait...");

		/* Calls the web service to load all divisions from the data base */
		new WSGetAllCategories().execute(null, null, null);

		getDataHandler = new Handler() {
			public void handleMessage(Message message) {

				if (message.what != -1) {

					final CategoryList categoryList[] = new CategoryList[categories
							.getCategoryNames().length + 1];

					categoryList[0] = new CategoryList("",
							"-- Select Category --");

					final MaterialList materialList[] = new MaterialList[materials
							.getMaterialNames().length + 1];

					materialList[0] = new MaterialList("",
							"-- Select Material --");

					for (int i = 1; i < categoryList.length; i++) {
						categoryList[i] = new CategoryList(
								categories.getCategoryIds()[i - 1],
								categories.getCategoryNames()[i - 1]);
						Log.v("categoryName : ", categoryList[i].getValue());
					}

					for (int i = 1; i < materialList.length; i++) {
						materialList[i] = new MaterialList(
								materials.getMaterialIds()[i - 1],
								materials.getMaterialNames()[i - 1]);
						Log.v("materialName : ", materialList[i].getValue());
					}

					/* Setting key - value pairs to divisionSpinner */
					ArrayAdapter<CategoryList> categoryAdapter = new ArrayAdapter<CategoryList>(
							AddProductInformationActivity.this,
							android.R.layout.simple_spinner_item, categoryList);

					Log.v("categoryAdapter : ", categoryAdapter.toString());

					select_cateogry_spinner.setAdapter(categoryAdapter);

					Log.v("select_cateogry_spinner : ",
							select_cateogry_spinner.toString());

					/* Setting key - value pairs to divisionSpinner */
					ArrayAdapter<MaterialList> materialAdapter = new ArrayAdapter<MaterialList>(
							AddProductInformationActivity.this,
							android.R.layout.simple_spinner_item, materialList);

					Log.v("materialAdapter : ", materialAdapter.toString());

					select_material_spinner.setAdapter(materialAdapter);

					Log.v("select_material_spinner : ",
							select_material_spinner.toString());

					progressDialog.dismiss();
				} else {
					/* Display connection failed alert message */
					connectionFailedAlert = Functions
							.getConnectionFailedAlert(
									AddProductInformationActivity.this,
									"Sorry. \nUnable to provide the service this time. Please try again latter.");

				}

			}
		};
	}

	public void onSubmitButtonClick(View v) {
		Intent mainScreen = new Intent(this, MobileBusinessPortalActivity.class);
		new WSAddNewProduct().execute(null, null, null);
		Toast.makeText(getApplicationContext(),"Product Successfully Added to the Portal", Toast.LENGTH_SHORT).show();
		getDataHandler = new Handler() {
			public void handleMessage(Message message) {

				if (message.what != -1) {
					Log.v("update result", "SUCCESS");					
				} else {
					Log.v("update result", "FAIL");

				}
			}
		};
		startActivity(mainScreen);
	}

	/*
	 * Asynchronous back ground process to retrieve the all divisions from the
	 * data base. If an exception occured sends and empty message to the web
	 * service client
	 */
	class WSGetAllCategories extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... params) {
			try {
				Log.v("calling - ", "getAllCategories");
				categories = BusinessPortalWebService.getAllCategories();
				materials = BusinessPortalWebService.getAllMaterials();
				Log.v("result - ", categories.toString());
				getDataHandler.sendMessage(getDataHandler.obtainMessage());
				return null;

			} catch (ConnectException e) {
				/*
				 * Sends an empty message to the web service client if an
				 * ConnectException occurred
				 */
				getDataHandler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("ConnectException", "ConnectException occured");
				e.printStackTrace();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				// Send an empty message if an exception occurred
				getDataHandler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("Exception", "Exception occured");
				e.printStackTrace();
			}
			return null;
		}
	}

	/*
	 * Asynchronous back ground process to retrieve the all divisions from the
	 * data base. If an exception occured sends and empty message to the web
	 * service client
	 */
	class WSAddNewProduct extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... params) {
			try {
				Log.v("select_cateogry_spinner.getSelectedItemId() - ", Long
						.toString(select_cateogry_spinner.getSelectedItemId()));
				Log.v("material.getSelectedItemId() - ", Long
						.toString(select_material_spinner.getSelectedItemId()));

				BusinessPortalWebService.addNewProduct(productNameEditText
						.getText().toString(), (int) select_cateogry_spinner
						.getSelectedItemId(), (int) select_material_spinner
						.getSelectedItemId(), 3, Integer
						.parseInt(quantityEditText.getText().toString()),
						Integer.parseInt(priceEditText.getText().toString()));
				return null;

			} catch (ConnectException e) {
				/*
				 * Sends an empty message to the web service client if an
				 * ConnectException occurred
				 */
				addProductHandler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("ConnectException", "ConnectException occured");
				e.printStackTrace();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				// Send an empty message if an exception occurred
				// addProductHandler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("Exception", "Exception occured");
				e.printStackTrace();
			}
			return null;
		}
	}

	class CategoryList {
		public CategoryList(String value, String spinnerText) {
			this.spinnerText = spinnerText;
			this.value = value;
		}

		public String getSpinnerText() {
			return spinnerText;
		}

		public String getValue() {
			return value;
		}

		public String toString() {
			return spinnerText;
		}

		String spinnerText;
		String value;
	}

	class MaterialList {
		public MaterialList(String value, String spinnerText) {
			this.spinnerText = spinnerText;
			this.value = value;
		}

		public String getSpinnerText() {
			return spinnerText;
		}

		public String getValue() {
			return value;
		}

		public String toString() {
			return spinnerText;
		}

		String spinnerText;
		String value;
	}
}
